package org.six11.ss.server.web;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.six11.util.adt.MultiState;

import static org.six11.ss.server.web.WebHandlerNames.*;

/**
 * This is the 'doorway' for all HTML page output. This servlet is responsible for determining which
 * action the user wants to take, and then invokes the correct handler for that action. If no such
 * action is known, it sends you to an 'unknown error' page.
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class WebHandlerServlet extends HttpServlet {

  private HashMap<String, WebHandler> actions;

  /**
   * Initialize things including the 'state' object, which is where all the handlers share data.
   */
  public WebHandlerServlet() {
    super();
    MultiState state = new MultiState();
    actions = new HashMap<String, WebHandler>();
    state.setValue(STATE, state);
    actions.put(ACTION_UNKNOWN, new UnknownHandler("/unknown.jsp", state));
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    ServletContext context = getServletContext();
    String what = getAttributeOrParam(req, PARAM_ACTION);
    if (actions.containsKey(what)) {
      actions.get(what).service(req, resp, context);
    } else {
      actions.get(ACTION_UNKNOWN).service(req, resp, context);
    }
  }

  private String getAttributeOrParam(HttpServletRequest req, String name) {
    String ret = (String) req.getAttribute(name);
    if (ret == null) {
      ret = req.getParameter(name);
    }
    return ret;
  }

}
